<template>
  <div class="ssc-list org-person-list">
    <div class="content">
      <div class="ssc-search">
        <a-form autocomplete="off">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="订阅组ID：">
                <a-select v-model:value="searchParam.appId" placeholder="订阅组">
                  <a-select-option v-for="item in applyList" :value="item.appId" :key="item.appId">{{ item.cname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="目录名称：">
                <a-input v-model:value="searchParam.catalogName" placeholder="请输入" :maxlength="20" allowClear />
              </a-form-item>
            </a-col>

            <a-col :span="6">
              <a-form-item label="目录类型：">
                <a-select v-model:value="searchParam.contentType" placeholder="请选择">
                  <a-select-option v-for="item in CatalogTypeList" :value="item.value" :key="item.value">{{ item.label }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-row justify="end">
                <a-button @click="clear()">重置</a-button>
                <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
              </a-row>
            </a-col>
            <a-col :span="8">
              <a-form-item label="选择日期：">
                <a-range-picker allowClear @change="panelChange" v-model:value="timeRange" show-time format="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="ssc-table">
        <div class="ssc-table-header">
          <span class="ssc-table-header-title">资产目录</span>
          <a-button type="primary" @click="add()">
            <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
            添加资产
          </a-button>
        </div>
        <a-table :columns="table.columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span>
                <a-popconfirm placement="leftBottom" v-if="record.state === ServiceType.Pass" ok-text="确定" cancel-text="取消" @confirm="updateServiceState(record, ServiceType.Offline)">
                  <template #title>
                    <p>下线确认</p>
                    <p class="w-[200px]">您确认要将服务下线吗？</p>
                  </template>
                  <a href="javascript:;">下线</a>
                </a-popconfirm>
                <a-divider type="vertical" v-if="record.state === ServiceType.Pass" />
                <a-popconfirm placement="leftBottom" v-if="record.state === ServiceType.Review" ok-text="确定" cancel-text="取消" @confirm="updateServiceState(record, ServiceType.Reject)">
                  <template #title>
                    <p>驳回确认</p>
                    <p class="w-[200px]">您确认要将服务驳回吗？</p>
                  </template>
                  <a href="javascript:;">驳回</a>
                </a-popconfirm>
                <a-divider type="vertical" v-if="record.state === ServiceType.Review" />
                <a-popconfirm placement="leftBottom" v-if="record.state === ServiceType.Review" ok-text="确定" cancel-text="取消" @confirm="updateServiceState(record, ServiceType.Pass)">
                  <template #title>
                    <p>通过确认</p>
                    <p class="w-[200px]">您确认要将服务通过吗？</p>
                  </template>
                  <a href="javascript:;">通过</a>
                </a-popconfirm>
                <a-divider type="vertical" v-if="record.state === ServiceType.Review" />
                <a @click="edit(record)">详情</a>
              </span>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <div class="modal">
      <Add v-model:visible="modalAdd.visible" @success="modalAdd.success" />
      <Edit v-model:visible="modalEdit.visible" :data="table.selectedRecord" @success="modalEdit.success" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
  import type { SelectProps } from 'ant-design-vue'
  import { message } from 'ant-design-vue'
  import type { Dayjs } from 'dayjs'
  import { onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import { requestSpaceAssetCatalogListByPage } from '/@/api/business/space'
  import { getApplyByPageEnum } from '/@/api/manage/openApiApp'
  import { requestGetServiceByPage, requestUpdateServiceState } from '/@/api/manage/openApiService'
  import { requestDeleteServiceType, requestServiceTypeList } from '/@/api/manage/openApiServiceType'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { ServiceType, ServiceTypeDesc, ServiceTypeList } from '/@/enums/serviceEnum'
  import { CatalogTypeList } from '/@/enums/spaceEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  const router = useRouter()
  import Add from './components/Add.vue'
  import Edit from './components/Edit.vue'
  type RangeValue = [Dayjs, Dayjs]
  const timeRange = ref<RangeValue>()
  const variable = reactive({
    category: {},
  })

  // 服务类型列表
  const classification = ref<SelectProps['options']>([])

  // onMounted(() => queryList())

  /** 查询服务类型列表 */
  const getServiceTypeList = async () => {
    const { responseCode, responseData } = await requestServiceTypeList({})
    if (responseCode === HttpCodeEnum.SUCCESS) {
      classification.value = (responseData || []).map((item) => ({
        label: item.name,
        value: item.id,
      }))
    }
  }
  getServiceTypeList()

  /** 查询条件 */
  const searchParam = reactive({
    catalogName: '',
    appId: null,
    contentType: null,
    startTime: '',
    endTime: '',
  })

  /** 表格配置 */
  const table = reactive({
    columns: [
      { title: '服务ID', dataIndex: 'uuid' },
      {
        title: '服务类型',
        dataIndex: 'type',
        customRender: ({ record }) => {
          const serviceType = (classification.value || []).filter((item: any) => item.value === record.type)
          return serviceType.length ? serviceType[0].label : ''
        },
      },
      { title: '服务名称', dataIndex: 'name' },
      {
        title: '服务状态',
        key: 'state',
        dataIndex: 'state',
        customRender: ({ record }) => {
          return ServiceTypeDesc[record.state]
        },
      },
      { title: '创建时间', dataIndex: 'createdTime', customRender: ({ record }) => record?.createdTime?.replace('T', ' ') || '--' },
      { title: '操作', key: 'action' },
    ],
    selectedRecord: {} as UserDeptListTypes.IResponse,
  })

  /** 表格分页hook */
  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<SpaceAssetCatalogTypes.IRequest, SpaceAssetCatalogTypes.IResponse[]>(searchParam, requestSpaceAssetCatalogListByPage)

  /**
   * 重置
   */
  const clear = () => {
    searchParam.catalogName = ''
    searchParam.appId = null
    searchParam.contentType = null
    searchParam.startTime = ''
    searchParam.endTime = ''
    timeRange.value = undefined
    search()
  }

  /**
   * 查询
   */
  const search = () => {
    queryList({ current: 1 })
  }

  const panelChange = (value, mode) => {
    console.log(value, mode)
    searchParam.startTime = mode[0]
    searchParam.endTime = mode[1]
  }
  /** 新增弹窗 */
  const modalAdd = reactive({
    visible: false,
    success: () => queryList(),
  })
  /**
   * 新增
   */
  const add = () => {
    modalAdd.visible = true
  }

  /** 编辑弹窗 */
  const modalEdit = reactive({
    visible: false,
    success: () => queryList(),
  })

  /**
   * 编辑
   */
  const edit = (record) => {
    table.selectedRecord = record
    modalEdit.visible = true
  }
  const applyList = ref<any[]>([])
  /**
   * 获取订阅组列表
   */
  const queryRecordList = () => {
    return getApplyByPageEnum({ pageSize: 30, pageIndex: 1 }).then((res) => {
      applyList.value = res?.responseData.records || []
      searchParam.appId = applyList.value[0]?.appId
      search()
    })
  }
  queryRecordList()
  const toAPIManage = (record) => {
    router.push({
      path: '/service-provider/serve/api',
      query: { serviceUuid: record.uuid },
    })
  }

  const deleteServiceType = async (service) => {
    const { responseCode } = await requestDeleteServiceType({ id: service.value })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('删除成功')
      getServiceTypeList()
    }
  }

  const updateServiceState = async (service, state) => {
    const { responseCode } = await requestUpdateServiceState({ uuid: service.uuid, state: state })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      queryList()
      message.success(`操作成功`)
    }
  }
</script>

<style lang="less" scoped>
  .org-person-list {
    display: flex;
  }

  .org {
    width: 200px;
    height: 100%;
    padding: 18px;
    background: #fff;

    .org-title {
      margin-bottom: 12px;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .anticon-plus-circle {
        cursor: pointer;
        color: #08979c;
      }
    }

    .classification {
      height: 40px;
      width: 100%;
      line-height: 40px;
      padding: 0 4px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;

      &.active {
        background: #cbf4f6;
        color: #08979c;
      }

      &:hover {
        background: #cbf4f6;
        color: #08979c;

        .action {
          // display: block;
          display: inline-block;
          min-width: 89px;
        }
      }

      .action {
        display: none;
        color: #08979c;
        font-size: 12px;
        text-align: right;

        > span {
          margin-left: 4px;
        }
        // .edit {
        // }

        .del {
          color: #f5222d;
        }
      }
    }
  }

  .content {
    flex: 1;
  }

  .ssc-search {
    margin-left: 16px;
    padding-bottom: 24px;
  }

  .ssc-table {
    margin-left: 16px;

    .dept-leader {
      position: relative;
      top: -2px;
      height: 20px;
      margin-right: 4px;
      padding: 0 8px;
      border: none;
      font-size: 10px;
      background: #87d068;
    }
  }
</style>
